package mysql;

import java.sql.*;
import java.util.*;

import model.*;

public class Query {
	public static String createTable(Connection con, String query){
		
		try{
			con.createStatement().executeUpdate(query);
		}
		catch(Exception e){
			return "테이블 생성 실패";
		}
		finally{
			try{
				if(con!=null)
					con.close();
			}
			catch(Exception e){
				
			}
		}
		return "테이블 생성 성공";
	}
	
	public static ArrayList<GuestBook> selectAll(Connection con){
		ArrayList<GuestBook> list = new ArrayList<GuestBook>();
		try{
			String query="select * from guestbook";
			ResultSet set = con.createStatement().executeQuery(query);
			while(set.next()){
				//mysql integer -> int
				int num = set.getInt("num");
				// mysql text -> String
				String content = set.getString("context");
				GuestBook gb = new GuestBook(num, content);
				list.add(gb);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
				if(con!=null)
					con.close();
			}
			catch(Exception e){
			}
		}
		return list;
	}
	
	public static int insert(Connection con, String content){
		int affectRow = 0;
		
		try{
			String query = "insert into guestbook (context) values (?)";
			PreparedStatement ps = con.prepareStatement(query);
			ps.setString(1, content);
			affectRow = ps.executeUpdate();
		}
		catch(Exception e){
		}
		finally{
			try{
				if(con!=null)
					con.close();
			}
			catch(Exception e){
			}
		}
		return affectRow;
	}
	
}
